package com.qzboot.backend.web.module.sys.controller;

import com.qzboot.backend.web.common.config.SysLog;
import com.qzboot.backend.web.module.sys.BaseSysController;
import com.qzboot.common.constant.SysConst;
import com.qzboot.common.support.WebResult;
import com.qzboot.facade.entity.SysUser;
import com.qzboot.facade.service.SysUserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Map;

/**
 * @author zengzhihong
 */
@RestController
@RequestMapping("/sysUser")
public class SysUserController extends BaseSysController {

    @Reference
    private SysUserService sysUserService;

    /**
     * 分页查询
     *
     * @param param
     * @return
     */
    @GetMapping("/listPage")
    @RequiresPermissions("sys:user:list")
    public WebResult listPage(@RequestParam Map<String, Object> param) {
        //非管理员只能查询自己创建的用户
        if (!SysConst.ADMIN_USER_ID.equals(getUserId())) {
            param.put("create_by_user_id", getUserId());
        }
        return WebResult.success(sysUserService.page(param));
    }

    /**
     * 新增
     *
     * @param entity
     * @return
     */
    @SysLog("新增用户")
    @PostMapping("/save")
    @RequiresPermissions("sys:user:save")
    public WebResult save(@Valid @RequestBody SysUser entity) {
        entity.setCreateByUserId(getUserId());
        entity.setCreateByUsername(getUser().getUsername());
        entity.setUpdateByUserId(getUserId());
        entity.setUpdateByUsername(getUser().getUsername());
        sysUserService.save(entity);
        return WebResult.success();
    }

    /**
     * 修改
     *
     * @param entity
     * @return
     */
    @SysLog("修改用户")
    @PostMapping("/updateById")
    @RequiresPermissions("sys:user:update")
    public WebResult updateById(@Valid @RequestBody SysUser entity) {
        entity.setCreateByUserId(getUserId());
        entity.setCreateByUsername(getUser().getUsername());
        entity.setUpdateByUserId(getUserId());
        entity.setUpdateByUsername(getUser().getUsername());
        sysUserService.updateById(entity);
        return WebResult.success();
    }

    /**
     * 通过ID删除
     *
     * @param id
     * @return
     */
    @SysLog("删除用户")
    @GetMapping("/removeById")
    @RequiresPermissions("sys:user:delete")
    public WebResult removeById(Long id) {
        sysUserService.removeById(id, getUserId());
        return WebResult.success();
    }

}
